var markerArray = [];
var reloadMaps = [];
var vResultsFrom = 0;
var numOfResults = 10;
var jsonInfo = [];
var infowindow;
var test;
var wrapperOrigHeight = $("#map_wrapper").height();

//when the page has loaded execute loadList()
$(document).ready(function() {
	//var newHeights = $(window).height()-$("#navigation").outerHeight()-$("#footer").outerHeight()-$("#header").outerHeight(true)-$("#map_wrapper").css("margin-top").replace("px", "");
	//$("#map_wrapper").height(newHeights);
	//$("#map_canvas").height(newHeights);

	//newHeights = newHeights -$("#marker_selection").outerHeight()-$("#locate_btn").outerHeight();
	//$("#list").height(newHeights);



	placeMarkers();

});

function placeMarkers() {

	var icon;
	// google maps stuff
	var sv = new google.maps.StreetViewService();

	//default position for map
	var latlng = new google.maps.LatLng(33.783409, -117.884674);
	//defualt options for map

	var defaultBounds = new google.maps.LatLngBounds(
			new google.maps.LatLng(33.783409, -117.884674),
			new google.maps.LatLng(33.783409, -117.884674));

	var input = document.getElementById('address');
	var options = {
			bounds: defaultBounds,
			types: ['geocode'],
			offset:-20
	};

	var autocomplete = new google.maps.places.Autocomplete(input, options);
	
	var myOptions = {
			zoom : 11,
			center : latlng,
			mapTypeId : google.maps.MapTypeId.ROADMAP
			//type of map HYBRID/ROADMAP/SATELLITE/TERRAIN
	};
	var map = new google.maps.Map(document.getElementById('map_canvas'),
			myOptions);
	
	autocomplete.bindTo('bounds' , map);

	infowindow = new google.maps.InfoWindow({
		content : "temp"
	});

	$.getJSON('get_map_points.php', function(output) {
		
		$.each(output, function(i) {
			var lat = output[i]['lat'];
			var lng = output[i]['lng'];
			var id = output[i]['id'];
			var orgName = output[i]['orgName'];
			var category = output[i]['category'];
			var address1 = output[i]['address1'];
			var address2 = output[i]['address2'];

			var latlng = new google.maps.LatLng(lat, lng);
			
			var marker = new google.maps.Marker({
				position : latlng,
				map : map,
				icon : getMarkerIcon(category),
				title : orgName
			});
			
			marker.html = $(output[i]['infobox']).html();
			marker.category = category;
			marker.id = id;
			marker.address = address1.concat(address2);
			
			
			google.maps.event.addListener(marker, 'click', function() {
				infowindow.setContent(this.html);
				infowindow.open(map, this);
				google.maps.event.addListener(infowindow, 'domready', function() { 
					var panorama = new google.maps.StreetViewPanorama(document.getElementById("streetview"), {
						navigationControl: false,
						enableCloseButton: false,
						addressControl: false,
						linksControl: false}
					); 
					panorama.setPosition(latlng); 
					panorama.setVisible(true);
				}); 
			});
			
			markerArray.push(marker);
		});
	});
}

function getMarkerIcon(category) {
	switch (category) {
	case "farm":
		return new google.maps.MarkerImage('./images/yellow.png',
				new google.maps.Size(32, 37), new google.maps.Point(0,0), 
				new google.maps.Point(16, 37));
	case "csa":
		return new google.maps.MarkerImage('./images/blue.png',
				new google.maps.Size(32, 37), new google.maps.Point(0,0), 
				new google.maps.Point(16, 37));
	case "farmers_market":
		return new google.maps.MarkerImage('./images/purple.png',
				new google.maps.Size(32, 37), new google.maps.Point(0,0), 
				new google.maps.Point(16, 37));
	case "orchards":
		return new google.maps.MarkerImage('./images/white.png',
				new google.maps.Size(32, 37), new google.maps.Point(0,0), 
				new google.maps.Point(16, 37));
	case "community_garden":
		return new google.maps.MarkerImage('./images/turq.png',
				new google.maps.Size(32, 37), new google.maps.Point(0,0), 
				new google.maps.Point(16, 37));
	default:
		return new google.maps.MarkerImage('./images/vineyard-2.png',
				new google.maps.Size(32, 37), new google.maps.Point(0,0), 
				new google.maps.Point(16, 37));
	}
}

function openWindow(i) {
	google.maps.event.trigger(markerArray[i], 'click');
}

function toggleVisible(Categories) {
	infowindow.close();
	
	for ( var i = 0; i < markerArray.length; i++) {
		var marker = markerArray[i];
		marker.setVisible(false);
		for( var j = 0; j < Categories.length; j++) {
			if(marker.category == Categories[j]) {
				marker.setVisible(true);
			}
		}
	}
}

function FindClosest(){
	$("#results").empty();
	var radius = document.getElementById("radius").value;
	var geocoder = new google.maps.Geocoder();
	var address = document.getElementById("address").value;
	var meterspermile = 1609.344;
	var newDistance = 0;
	var visibleMarkers = [];
	var tempHtml;
	if($("#address").val() == "") {
		$("#results").append("<div style = \"color : red\">*Please Enter an Address*</div>");
	} else {
		geocoder.geocode({'address':address},function(results, status){
			if (status == google.maps.GeocoderStatus.OK) {
				if(results.length == 1) {
					toggleVisible($("#categories").val());
					$.each(markerArray,function(i,value) {
						if(value.getVisible()){
							newDistance = google.maps.geometry.spherical.computeDistanceBetween(results[0].geometry.location,value.position)/meterspermile;
							if (newDistance > radius) {
								value.setVisible(false);
							} else {
								value.distance = newDistance;
								value.MarkerArrayPosition = i;
								visibleMarkers.push(value);
							}
						}
					});

					visibleMarkers.sort(sortNumber);
					for(var i = 0; i < visibleMarkers.length; i++) {
						tempHtml = visibleMarkers[i]['title'];
						
						var address = results[0].formatted_address;
						address = address.replace(/\s+/g,"+");
						address = address.replace(/,/g,"");
						var destination =  visibleMarkers[i]['address'];
						destination = destination.replace(/\s+/g,"+");
						destination = destination.replace(/,/g,"");
						
						var resultItem = "<div id=\"result-item\" class=\""+(i%2 == 0?"odd-num":"even-num")+"\"><div id=\"result-item-header\" onclick = \"openWindow("+visibleMarkers[i].MarkerArrayPosition+")\"><div id=\"result-item-header-number\" class=\""+(i>98?"digits-3-num":"digits-2-num")+"\"><a href=\"#\" >"+(i+1)+"</a></div><div id=\"result-item-header-title\" class=\""+(i>98?"digits-3-title":"digits-2-title")+"\"><a href= \"#\">"+tempHtml+"</a></div></div><div id=\"result-item-body\">"+visibleMarkers[i]['address']+" ("+visibleMarkers[i]['distance'].toFixed(2)+" mi)<br/><a href=\"http://maps.google.com/maps?saddr="+address+"&daddr="+destination+"\" target=\"_blank\" >Get Directions</a></div></div>";
						$("#results").append(resultItem);
					}
				} else {
					for(var i = 0; i<results.length;i++){
						$("#results").append("did you mean?<br>");
					}
				}
			} else {
				$("#results").append("<div style = \"color : red\">*Address Not Found*</div>");
			}
			$("#map_wrapper").height(625 + $("#results").height());
		});	
	}
}	

function sortNumber(a,b) {
	return a.distance - b.distance;
}

